﻿using IM.Easy.Core.Result;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Core.Filters
{
    public partial class ApiActionFilter : ActionFilterAttribute, IActionFilter
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            Console.WriteLine("ApiActionFilter:OnActionExecuting");
            // 在操作执行之前的逻辑
        }

        public override void OnActionExecuted(ActionExecutedContext context)
        {
            //throw new Exception("异常测试");
            if (context.Result is ObjectResult objectResult)
            {
                var result = objectResult.Value;
                if (result != null && result is not ApiResult)
                {
                    var apiResult = ApiResult<object>.Success(result);
                    context.Result = new ObjectResult(apiResult)
                    {
                        StatusCode = objectResult.StatusCode
                    };
                }
            }
            else if (context.Result is EmptyResult)
            {
                var apiResult = ApiResult.Success();
                context.Result = new ObjectResult(apiResult) { StatusCode = 200 };
            }
        }
    }

}
